/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wh.ironcity.services;

import java.util.List;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Aganguly
 */
@WebService
@Stateless()
public class Inventory {

    //@PersistenceUnit(name = "Warehouse_IronCityPU")
    //@PersistenceUnit(unitName = "Warehouse_IronCityPU")
    @PersistenceContext(unitName = "Warehouse_IronCityPU")
    EntityManager em;

    /**
     * Web service operation
     */
    @WebMethod(operationName = "getAvailableStocks")
    public int getAvailableStocks(@WebParam(name = "ItemName") String ItemName) {
        int itemCount = -1;
        //check how many records are available
        List<Item> items = getItemsByName(ItemName);
        if (items != null) {
            itemCount = items.size();
        }
        return itemCount;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "reduceInventory")
    public Boolean reduceInventory(@WebParam(name = "itemName") String itemName, @WebParam(name = "quantity") int quantity) {
        boolean isSuccess = false;
        //add some code to update the records for an item
        ////check if the item is available here or not
        boolean isAvailable = isItemAvailable(itemName, quantity);
        if (isAvailable) {
            //reduce the inventory of this item by the specified quantity
            isSuccess = true;
        }
        return isSuccess;
    }

    private boolean isItemAvailable(String itemName, int quantity) {
        //check if the item is available in this quantity
        List<Item> searchedItems = getItemsByName(itemName);
        if (searchedItems == null) {
            return false;
        }
        if (searchedItems.size() >= quantity) {
            return true;
        } else {
            return false;
        }
    }

    private List<Item> getItemsByName(String name) {
        Query searchQuery = em.createQuery("SELECT i FROM Item i WHERE i.itemName = :itemName");
        searchQuery.setParameter("itemName", name);
        List<Item> searchedItems = (List<Item>) searchQuery.getResultList();
        return searchedItems;
    }

    /**
     * Web service operation
     */
    @WebMethod(operationName = "addItem")
    public Boolean addItem(@WebParam(name = "itemName") String itemName, @WebParam(name = "stockQuantity") int stockQuantity) {
        boolean result = false;
        Item newItem = new Item();
        newItem.setItemName(itemName);
        newItem.setQuantity(stockQuantity);
        try {
            em.persist(newItem);
            result = true;
        } catch (Exception ex) {
            result = false;
        }
        return result;
    }
}
